﻿using System;
using System.Web;
using System.Web.Security;
using INHollandair.Core.Enum;
using INHollandair.Core.Models;
using INHollandair.Core.Services;

namespace INHollandair
{
    public partial class SiteMaster : System.Web.UI.MasterPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (HttpContext.Current.User.Identity.IsAuthenticated)
            {
                btn_UserName.Text = HttpContext.Current.User.Identity.Name;
                btn_UserName.PostBackUrl = "~/Account/Settings.aspx";
                pnl_LoggedIn.Visible = true;
                pnl_NotLoggedIn.Visible = false;

                //Set MultiView
                MultiViewDropDown.SetActiveView(userLoggedIn);
            }
            else
            {
                pnl_LoggedIn.Visible = false;
                pnl_NotLoggedIn.Visible = true;

                //Set MultiView
                MultiViewDropDown.SetActiveView(userNotLoggedIn);
            }
        }

        protected void LoginClick(object sender, EventArgs e)
        {
            if (!IsIpBlocked())
            {
                string user = Server.HtmlEncode(txt_UserName.Text);
                string pass = Server.HtmlEncode(txt_Password.Text);

                bool rememberMe = chk_rememberMe.Checked;

                if (user.Length > 0 && pass.Length > 0)
                {
                    UserService svc = new UserService();

                    string salt = svc.GetUserSaltByName(user);
                    string hash = salt == null ? String.Empty : EncryptionUtils.Hash(pass, salt);

                    if (svc.Login(user, hash).Equals(LoginEnum.Succes))
                    {
                        string redirectUrl = FormsAuthentication.GetRedirectUrl(user, rememberMe);
                        FormsAuthentication.SetAuthCookie(user, rememberMe);
                        Session["attempts"] = 5;
                        Response.Redirect(redirectUrl);
                    }
                    else
                    {
                        Session["attempts"] = (Session["attempts"] == null) ? 1 : ((int)Session["attempts"]) + 1;
                    }
                }
            }
            Response.Redirect("~/Account/Login.aspx");
        }

        protected void LogoutClick(object sender, EventArgs e)
        {
            if (HttpContext.Current.User.Identity.IsAuthenticated)
            {
                Session.Abandon();
                FormsAuthentication.SignOut();
                Response.Redirect(Request.Url.AbsoluteUri);
            }
        }

        public bool IsIpBlocked()
        {
            int maxAttempts = (Session["attempts"] == null) ? 0 : ((int)Session["attempts"]);
            BlockedIpService svc = new BlockedIpService();
            BlockedIp blockedIp = svc.GetBlockedIpByIp(Request.UserHostAddress);
            if (blockedIp != null)
            {
                if (blockedIp.Created.AddMinutes(5) >= DateTime.Now)
                {
                    blockedIp.Created = DateTime.Now;
                    svc.UpdateBlockedIp(blockedIp);
                    return true;
                }
                svc.RemoveBlockedIp(blockedIp);
            }
            else if (maxAttempts >= 4)
            {
                blockedIp = new BlockedIp
                {
                    Ip = Request.UserHostAddress,
                    Created = DateTime.Now
                };
                svc.InsertBlockedIp(blockedIp);
                LogEvent();
                return true;
            }
            return false;
        }

        private void LogEvent()
        {
            string ip = Request.UserHostAddress;

            EventLogService svc = new EventLogService();
            EventLog eventToLog = new EventLog
            {
                Description = string.Format("IP: {0} || Message: Login attempt limit exceeded..", ip),
                DateLogged = DateTime.Now
            };
            svc.InsertEventLog(eventToLog);
        }
    }
}
